package com.ho1ho.audioexample;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CaptureImage extends AppCompatActivity {

    private static final String TAG = CaptureImage.class.getSimpleName();

    // Keep track of cropping intent
    private static final int PIC_CROP = 3;

    private ImageView iv;
    private Uri mImageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture_image);

        iv = findViewById(R.id.iv);
//        onCapture();
        takePhoto();
    }

    public void onCapture() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//用来打开相机的Intent
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            startActivityForResult(takePhotoIntent, 0x1234);//启动相机
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if(requestCode==0x1234&&resultCode==RESULT_OK){
//            /*缩略图信息是储存在返回的intent中的Bundle中的，
//             * 对应Bundle中的键为data，因此从Intent中取出
//             * Bundle再根据data取出来Bitmap即可*/
//            Bundle extras = data.getExtras();
//            Bitmap bitmap = (Bitmap) extras.get("data");
//            iv.setImageBitmap(bitmap);
//        }

        if (requestCode == 0x1234 && resultCode == RESULT_OK) {
//            try {
//                /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
//                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
//                iv.setImageBitmap(bitmap);//显示到ImageView上
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
            performCrop();
        } //user is returning from cropping the image
        else if (requestCode == PIC_CROP) {
            try {
//            //get the returned data
//            Bundle extras = data.getExtras();
//            //get the cropped bitmap
//            Bitmap bitmap = (Bitmap) extras.get("data");
//                iv.setImageBitmap(bitmap);//显示到ImageView上

                InputStream is = getContentResolver().openInputStream(mImageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                iv.setImageBitmap(bitmap);//显示到ImageView上
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // ========================================

    private void takePhoto() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            File imageFile = createImageFile();//创建用来保存照片的文件
            Log.w(TAG, "Image saved path=" + imageFile.getAbsolutePath());
//            boolean deleteFlag = imageFile.delete();
//            Log.w(TAG, "deleteFlag=" + deleteFlag);
            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*7.0以上要通过FileProvider将File转化为Uri*/
                    mImageUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", imageFile);
                } else {
                    /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
                    mImageUri = Uri.fromFile(imageFile);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(takePhotoIntent, 0x1234);//打开相机
            }
        }
    }

    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("image", "url=" + imageFile.getAbsoluteFile());
        return imageFile;
    }

    private void performCrop() {
        try {
            //call the standard crop action intent (the user device may not support it)
            Intent cropIntent = new Intent("com.android.camera.action.CROP");


            //indicate image type and Uri
            cropIntent.setDataAndType(mImageUri, "image/*");
            //set crop properties
//            cropIntent.putExtra("crop", "true");
//            //indicate aspect of desired crop
//            cropIntent.putExtra("aspectX", 1);
//            cropIntent.putExtra("aspectY", 1);
//            //indicate output X and Y
//            cropIntent.putExtra("outputX", 256);
//            cropIntent.putExtra("outputY", 256);
//            //retrieve data on return
//            cropIntent.putExtra("return-data", true);
            // 授权应用读取 Uri，这一步要有，不然裁剪程序会崩溃
            cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //start the activity - we handle returning in onActivityResult
//             startActivityForResult(cropIntent, PIC_CROP);


            File imageFile = createImageFile();//创建用来保存照片的文件
            Log.w(TAG, "Cropped image saved path=" + imageFile.getAbsolutePath());
//            boolean deleteFlag = imageFile.delete();
//            Log.w(TAG, "deleteFlag=" + deleteFlag);
            if (imageFile != null) {
                // 照片 截取输出的outputUri， 只能使用 Uri.fromFile，不能用FileProvider.getUriForFile
                mImageUri = Uri.fromFile(imageFile);
                cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(cropIntent, PIC_CROP);//打开相机
            }


        } catch (ActivityNotFoundException anfe) {
            anfe.printStackTrace();
            //display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        }
    }
}
